<template>
  <div class="ele-body">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-split-layout
        width="226px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
        :style="{ minHeight: 'calc(100vh - 152px)' }"
      >
        <div>
          <a-tabs v-model:active-key="active" size="large">
            <a-tab-pane tab="对讲组" key="public">
              <div class="ele-border-split tree-list">
                <a-tree
                  :tree-data="data"
                  v-model:expanded-keys="expandedRowKeys"
                  v-model:selected-keys="selectedRowKeys"
                  @select="onTreeSelect"
                />
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        <template #content>
          <audio-file-list v-if="currentGroupName" :group-list="groupList" :group-id="current?.id" :group-name="currentGroupName" :group-no="currentGroupNo" ref="audioFileListRef"/>
        </template>
      </ele-split-layout>
    </a-card>
  </div>
</template>

<script setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import { messageLoading, toTreeData, eachTreeData } from 'ele-admin-pro/es';
  import audioFileList from './components/audio-file-list.vue';
  import {
    listGroups,
    removeGroup
  } from '@/api/audio/group';

  // 加载状态
  const loading = ref(true);

  // 树形数据
  const data = ref([]);

  // 树展开的key
  const expandedRowKeys = ref([]);

  // 树选中的key
  const selectedRowKeys = ref([]);

  //  声明子组件的 ref
  const audioFileListRef = ref(null);

  // 选中数据
  const current = ref(null);

  // 当前选中所属组织
  const currentGroupName = ref(null);

  // 对讲组编号
  const currentGroupNo = ref(null);

  let groupList = ref([]);

  // 是否显示表单弹窗
  const showEdit = ref(false);

  // 编辑回显数据
  const editData = ref(null);

  // tab 页选中
  const active = ref('public');

  /* 查询 */
  const query = () => {
    loading.value = true;
    listGroups()
      .then((list) => {
        console.log('======listGroup=====',list);
        loading.value = false;
        // Step 1: 转换列表数据为以 groupOrg 为键的对象
        const groupedByOrg = {};
        // 用于存储所有节点的映射表
        const nodesMap = {};
        const treeData = [];
        groupList = list;
        // 第一遍遍历：创建所有节点并存入映射表
        list.forEach((item) => {
          // ========== 外层按 groupOrg 分组 ==========
          if (!groupedByOrg[item.groupOrg]) {
            // 每个分组存储 { map: 节点映射表, roots: 根节点列表 }
            groupedByOrg[item.groupOrg] = {
              map: {},     // 存储当前组织下所有节点 (id => node)
              roots: []    // 存储当前组织下的根节点 (parent_id不存在或不在本组织)
            };
          }
          const currentOrg = groupedByOrg[item.groupOrg];

          // ========== 创建节点并存入映射表 ==========
          const newItem = {
            key: item.id,
            value: item.id,
            title: item.groupName,
            children: [], // 初始化子节点
            ...item       // 保留原始数据
          };
          currentOrg.map[item.id] = newItem;
        });

        // ========== 第二遍遍历：构建组织内的树结构 ==========
        list.forEach((item) => {
          const currentOrg = groupedByOrg[item.groupOrg];
          const currentNode = currentOrg.map[item.id];
          const parentId = item.parentId;

          // 尝试在 同一个组织内 查找父节点
          if (parentId && currentOrg.map[parentId]) {
            // 找到父节点，将当前节点加入其 children
            currentOrg.map[parentId].children.push(currentNode);
          } else {
            // 没有父节点或父节点不在本组织，作为根节点
            currentOrg.roots.push(currentNode);
          }
        });

        console.log('======groupedByOrg=====',groupedByOrg);
        // Step 2: 将对象转换为树形结构
        for (const org in groupedByOrg) {
          if (groupedByOrg.hasOwnProperty(org)) {
            treeData.push({
              title: org,  // 根节点的标题为 groupOrg
              key: org,    // 根节点的 key 可以设置为 groupOrg 或其他唯一标识符
              children: groupedByOrg[org].roots   // 子节点为属于该 groupOrg 的组
            });
          }
        }

        // 更新 expandedRowKeys, selectedRowKeys, current 等变量
        // const eks = treeData.flatMap(node => node.children.map(child => child.key));
        const eks = treeData.map(node => node.key);
        console.log('=====eks=====',eks);
        expandedRowKeys.value = eks.length ? eks : [];  // 如果 eks 为空数组，则直接设置为空数组
        data.value = treeData;
        console.log("group======treeData===>",treeData);
        if (treeData.length) {
          // 如果有数据，选择第一个 groupOrg 下的第一个组
          const firstOrg = treeData[0];
          currentGroupName.value = firstOrg.key;
          currentGroupNo.value = null;
          if (firstOrg.children.length) {
            selectedRowKeys.value = [firstOrg.children[0].key];
            currentGroupNo.value = firstOrg.children[0].groupNo;
            current.value = firstOrg.children[0];
          } else {
            selectedRowKeys.value = [];
            current.value = null;
          }
        } else {
          selectedRowKeys.value = [];
          currentGroupNo.value = null;
          current.value = null;
        }
        console.log("data======",data);
        console.log("treeData======",treeData);
        console.log("currentGroupName======",currentGroupName.value);
        console.log("currentGroupNo======",currentGroupNo.value);
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  /* 选择数据 */
  const onTreeSelect = () => {
    let foundNodes = null; // 用于存储所有找到的选中节点
    eachTreeData(data.value, (d) => {
      if (typeof d.key === 'number' && selectedRowKeys.value.includes(d.key)) {
        foundNodes = d;
      }
      current.value = foundNodes ?? null;
      currentGroupName.value = foundNodes ? current.value?.groupName : selectedRowKeys.value[0];
      currentGroupNo.value = foundNodes ? current.value?.groupNo : null;
    });
    console.log('onTreeSelect=====foundNodes===>',foundNodes);
    console.log('onTreeSelect=====current===>',current.value, currentGroupName.value, currentGroupNo.value);
    audioFileListRef.value.reload({groupNo: currentGroupNo.value});
  };

  /* 打开编辑弹窗 */
  const openEdit = (item) => {
    editData.value = item ?? null;
    showEdit.value = true;
  };

  /* 删除 */
  const remove = () => {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的对讲组吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        removeGroup(current.value?.key)
          .then((msg) => {
            hide();
            message.success(msg);
            query();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  query();
</script>

<script>
  export default {
    name: 'SystemOrganization'
  };
</script>

<style lang="less" scoped>
  .tree-list {
    padding: 12px 6px;
    height: calc(100vh - 242px);
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }
</style>
